import 'package:flutter/material.dart';

class RecyclerView extends StatefulWidget {

  _RecyclerView recycler;

  /**
   * @param dataList:数组
   * @param spanCount:每一行元素个数
   * @param ratio:元素宽高比
   * @param viewBinderImpl:继承ViewBinder
   */
  RecyclerView(dataList, spanCount, ratio, ViewBinder viewBinderImpl) {
    recycler = _RecyclerView(dataList, spanCount, ratio, viewBinderImpl);
    viewBinderImpl.recyclerView = this;
  }

  void notifyDataChange(VoidCallback fn) {
    recycler.update(fn);
  }

  @override
  _RecyclerView createState() {
    return recycler;
  }
}

class _RecyclerView extends State<RecyclerView> {

  List dataList;
  int spanCount;
  double ratio;
  ViewBinder viewBinder;

  void update(VoidCallback fn) {
    setState(() {
      fn();
    });
  }

  _RecyclerView(this.dataList, this.spanCount, this.ratio, this.viewBinder) {
    //
  }

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: spanCount,
            childAspectRatio: ratio
        ),
        itemCount: dataList.length,
        itemBuilder: (context, index) {
          return viewBinder.bindView(context, index, dataList);
        }
    );
  }
}

abstract class ViewBinder {

  RecyclerView recyclerView;

  bindView(context, index, dataList);
}